

package com.zdkj.subway.stm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.constant.SecurityConstants;
import com.zdkj.common.core.exceltools.IExcelExport;
import com.zdkj.common.core.util.R;
import com.zdkj.common.core.util.SpringContextHolder;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.subway.stm.dto.out.SwPmLongPeriodSettlementDTO;
import com.zdkj.subway.stm.entity.SwStIncomeSettle;
import com.zdkj.subway.stm.fegin.SupportService;
import com.zdkj.subway.stm.service.SwStIncomeSettleService;
import com.zdkj.subway.stm.util.DateUtilStm;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.List;


/**
 * 收入结算 ADVANCE ONE-WAY TICKET
 *
 * @author Gofe
 * @date 2020-02-12 10:38:29
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swstincomesettle")
@Api(value = "swstincomesettle", tags = "收入结算管理")
@Slf4j
public class SwStIncomeSettleController {

    private final SwStIncomeSettleService swStIncomeSettleService;

    private final SupportService supportService;

    /**
     * 分页查询
     *
     * @param page             分页对象
     * @param swStIncomeSettle 收入结算
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStIncomeSettlePage(Page page, SwStIncomeSettle swStIncomeSettle) {
        return R.ok(swStIncomeSettleService.page(page, Wrappers.query(swStIncomeSettle)));
    }


    /**
     * 通过id查询收入结算
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStIncomeSettleService.getById(id));
    }

    /**
     * 新增收入结算
     *
     * @param swStIncomeSettle 收入结算
     * @return R
     */
    @ApiOperation(value = "新增收入结算", notes = "新增收入结算")
    @SysLog("新增收入结算")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('stm_sw_st_income_settle_add')")
    public R save(@RequestBody SwStIncomeSettle swStIncomeSettle) {
        return R.ok(swStIncomeSettleService.save(swStIncomeSettle));
    }

    /**
     * 修改收入结算
     *
     * @param swStIncomeSettle 收入结算
     * @return R
     */
    @ApiOperation(value = "修改收入结算", notes = "修改收入结算")
    @SysLog("修改收入结算")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('stm_sw_st_income_settle_edit')")
    public R updateById(@RequestBody SwStIncomeSettle swStIncomeSettle) {
        return R.ok(swStIncomeSettleService.updateById(swStIncomeSettle));
    }

    /**
     * 通过id删除收入结算
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除收入结算", notes = "通过id删除收入结算")
    @SysLog("通过id删除收入结算")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_income_settle_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swStIncomeSettleService.removeById(id));
    }

    /**
     * 根据原始数据（
     * 1.TVM钱箱清点记录，
     * 2.TVM日结账单数据，
     * 3.售票员日结算数据，
     * 4.手工清出数据，
     * 6.互联网售票机数据）
     * 结算
     *
     * @param beginTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    @GetMapping("/settle/{beginTime}/{endTime}")
    @SysLog("结算")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_income_settle_settle')")
    @ApiOperation(value = "结算", notes = "统计原始数据信息到收入结算")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "beginTime", value = "开始时间", required = true, dataType = "Date", paramType = "path"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true, dataType = "Date", paramType = "path"),
    })
    public R settle(@PathVariable Date beginTime, @PathVariable Date endTime) {
        return swStIncomeSettleService.settle(beginTime, endTime);
    }

    /**
     * 提交原始数据（
     * 1.TVM钱箱清点记录，
     * 2.TVM日结账单数据，
     * 3.售票员日结算数据，
     * 4.手工清出数据，
     * 5.互联网售票机数据）
     * 修改状态
     *
     * @param id
     * @return
     */
    @GetMapping("/settleCommit/{id}")
    @SysLog("提交")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_income_settle_settle_commit')")
    @ApiOperation(value = "提交", notes = "提交原始数据到线网")
    public R settleCommit(@PathVariable Integer id) {
        return swStIncomeSettleService.settleCommit(id);
    }

    /**
     * 外部调用接口
     * 修改原始数据（
     * 1.TVM钱箱清点记录，
     * 2.TVM日结账单数据，
     * 3.售票员日结算数据，
     * 4.手工清出数据，
     * 5.互联网售票机数据）
     * 状态
     *
     * @param state 要修改的状态
     * @return
     */
    @GetMapping("/settleCommit/{state}")
    @SysLog("修改原始数据状态")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_income_settle_update_state')")
    @ApiOperation(value = "修改原始数据状态(外部调用接口)", notes = "修改原始数据状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "state", value = "修改状态", required = true, dataType = "Integer", paramType = "path")
    })
    public R updateOriginalState(@PathVariable Integer state) {
        return swStIncomeSettleService.updateOriginalState(state);
    }

    /**
     * 导出收入结算信息
     *
     * @param swStIncomeSettle
     * @return
     */
    @GetMapping("/export")
    @SysLog("导出")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_income_settle_export')")
    @ApiOperation(value = "导出", notes = "导出收入结算信息")
    public R exportExcel(SwStIncomeSettle swStIncomeSettle) {
        List<SwStIncomeSettle> swStIncomeSettleList = swStIncomeSettleService.list(Wrappers.query(swStIncomeSettle));
        IExcelExport excelExport = SpringContextHolder.getBean("commonExcelExport");
        Workbook workbook = excelExport.parse(swStIncomeSettleList);
        ByteArrayOutputStream os = null;
        try {
            //根据路径创建输出流
            os = new ByteArrayOutputStream();
            workbook.write(os);
            return R.ok("1", "收入结算信息导出成功");
        } catch (Exception e) {
            log.error("error", e);
            return R.failed("导出失败:" + e.getMessage());
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (Exception e) {
                log.error("workbook 流关闭失败");
            }
        }
    }

    /**
     * 定时任务调用，TVM结算，如果车站没有提交结算，到设定的结算周期，系统自动按结算周期结算
     *
     * @return
     */
    @ApiOperation(value = "每天系统自动按设定结算周期结算", notes = "每天系统自动按设定结算周期结算")
    @Inner
    @PostMapping("/calc")
    public R calcIncomeSettle() {
        QueryWrapper<SwStIncomeSettle> wrapper = new QueryWrapper<SwStIncomeSettle>();
        wrapper.eq("isSubmit", 0);
        wrapper.eq("delFlag", 0);
        List<SwStIncomeSettle> swStIncomeSettleList = swStIncomeSettleService.list(wrapper);
        for (SwStIncomeSettle swStIncomeSettle : swStIncomeSettleList) {
            int day = DateUtilStm.getDayInterval(DateUtilStm.asDate(swStIncomeSettle.getSettleStartDate()), new Date());
            SwPmLongPeriodSettlementDTO settlementDTOS = supportService.getLongPeriodSettlement(swStIncomeSettle.getStationCode(), swStIncomeSettle.getLineCode(), SecurityConstants.FROM_IN).getData();
            int setday=Integer.valueOf(settlementDTOS.getTvmSettlementTerm());
            if (day==setday) {
                swStIncomeSettle.setIsSubmit(1);
                swStIncomeSettleService.save(swStIncomeSettle);
            }

        }
        return R.ok();
    }

}
